/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.misc;

import java.util.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.sql.*;

import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;

import nfse.*;
import nfse.index.IndexBuildInput;
import nfse.index.IndexBuilder;

public class TempTableMetadataSync {

    public static void main(String[] args) {
        //while (true) {
            try {
                boolean migrated = false;
                NetFSE.configure(args[0]);

                String nodeConfigPath = args[1];
                File config2 = new File(nodeConfigPath);
                if (config2.exists()) {
                    NetFSE.processNodeConfigFile(config2);
                } else {
                    throw (new Exception("The specified node configuration file does not exist: '" + nodeConfigPath
                            + "'"));
                }

                MetaDatabase mdb = MetaDatabase.create();

                SensorInfo[] sensors = NetFSE.getSensorInfo();
                int[] types = NetFSE.getTypes();
                for (int i = 0; i < types.length; i++) {
                    String typeName = NetFSE.getTypeName(types[i]).toLowerCase();
                    String typeClassName = NetFSE.getTypeClassName(types[i]);
                    NetFSERecord rec = (NetFSERecord) NetFSE.TYPE_CLASSES.get(new Integer(types[i]));
                    for (int j = 0; j < sensors.length; j++) {
                        if (sensors[j].getToolID() == rec.getTypeID()) {
                            try {
                                Connection c = DriverManager.getConnection("jdbc:mysql://localhost" + "/" + typeName, NetFSE.DYNAMIC_DB_USER,
                                        NetFSE.DYNAMIC_DB_PASSWORD);
                                Statement s = c.createStatement();
                                Statement s2 = c.createStatement();

                                int maxRun = -1;
                                int maxRunIdx = -1;
                                int idx = 0;
                                Vector temp = new Vector();
                                ResultSet rs = s.executeQuery("show tables");
                                while (rs.next()) {
                                    String name = rs.getString(1);
                                    String[] tokens = name.split("_");

                                    if (tokens.length == 3 && !name.endsWith("Old") && !name.endsWith("New")) {
                                        int sensor = Integer.parseInt(tokens[0]);
                                        int node = Integer.parseInt(tokens[1]);
                                        int run = Integer.parseInt(tokens[2]);
                                        if (run > maxRun) {
                                            maxRun = run;
                                            maxRunIdx = idx;
                                        }
                                        temp.addElement(name);
                                        idx++;
                                    }
                                }
                                rs.close();
                                //String maxName = (String)temp.elementAt(maxRunIdx);
                                //s.execute("alter table " + maxName + " engine=InnoDB");
                                temp.removeElementAt(maxRunIdx);

                                for (int x = 0; x < temp.size(); x++) {
                                    String name = (String) temp.elementAt(x);
                                    ResultSet rs2 = s2.executeQuery("select max(startts), min(startts) from " + name);
                                    if (rs2.next()) {
                                        Timestamp maxTS = rs2.getTimestamp("max(startts)");
                                        Timestamp minTS = rs2.getTimestamp("min(startts)");
                                        System.out.println("Processing: " + name + " (" + minTS + "-" + maxTS + ")");
                                        mdb.addTempTable(name, NetFSE.NODE_ID, sensors[j].getSensorID());
                                        mdb.setTempTableTimestamps(name, minTS, maxTS);
                                    }
                                    rs2.close();
                                }
                                rs.close();
                                s2.close();
                                s.close();
                                c.close();
                            } catch (Exception e) {
                                // e.printStackTrace();
                            }
                        }
                    }

                }
                mdb.closeConnection();
                

            } catch (Exception E) {
                E.printStackTrace();
            }
        //}
    }

}
